package cn.jingyuan.bee.spring.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;


/**
 * Spring 上下文工具
 */
public class SpringContextSupport implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private SpringContextSupport() { }

    /**
     * 根据 bean 的名称获取 bean 实例
     *
     * @param name Bean的名称
     * @param <T> Bean类对象
     *
     * @return 实例
     */
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        checkApplicationContext();
        return applicationContext.getBean(name, requiredType);
    }

    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBeansOfType(clazz);
    }

    @Override
    public final synchronized void setApplicationContext(ApplicationContext applicationCon) {
        applicationContext = applicationCon;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicationContext not inject");
        }
    }

}